//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!

use std::str::FromStr;
use std::time::SystemTime;

use chrono::{prelude::*};
use chrono_tz::Asia::Shanghai;
use chrono_tz::{Tz};
use crate::utils::settings::Settings;

/// get current time stamp
#[inline]
pub fn timestamp() -> u64 {
    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
        Ok(n) => { n.as_secs() }
        Err(_) => { 0 }
    }
}

/// 要求输入: 2019-11-11 10:10:10
#[inline]
pub fn from_str(datetime_str: &str) -> DateTime<Local> {
    let datetime = NaiveDateTime::parse_from_str(datetime_str, "%Y-%m-%d %H:%M:%S")
        .expect("Failed to parse datetime");
    Local.from_local_datetime(&datetime).unwrap()
}

/// 当前的时间字符串
#[inline]
pub fn to_string() -> String {
    let local: DateTime<Local> = Local::now();
    local.format("%Y-%m-%d %H:%M:%S").to_string()
}

/// 格式化时间
#[inline]
pub fn format(format_str: &str) -> String {
    let local: DateTime<Local> = Local::now();
    local.format(format_str).to_string()
}

/// 当前时间
#[inline]
pub fn now() -> DateTime<Tz> {
    let tz = timezone();
    Utc::now().with_timezone(&tz)
}

/// 得到时分秒
#[inline]
pub fn time() -> (u32, u32, u32) {
    let now = now();
    (now.hour(), now.minute(), now.second())
}

/// 得到年月日
#[inline]
pub fn date() -> (u32, u32, u32) {
    let now = now();
    (now.year() as u32, now.month() as u32, now.day() as u32)
}

// 时区
pub fn timezone() -> Tz {
    let setting = Settings::get();
    let timezone = &setting.time.timezone;
    let tz = Tz::from_str(timezone).unwrap();
    tz
}

/// 获取当前日期
/// 格式：2020/01/01
pub fn current_date() -> String {
    // 获取当前本地时间
    let tz = timezone();
    let now = Utc::now().with_timezone(&tz);
    // 格式化时间为字符串
    let date_str = now.format("%Y/%m/%d").to_string();
    date_str
}

pub fn current_date_time() -> String {
    // 获取当前本地时间
    let tz = timezone();
    let now = Utc::now().with_timezone(&tz);
    // 格式化时间为字符串
    let date_time_str = now.format("%Y/%m/%d %H:%M:%S").to_string();
    date_time_str
}

pub fn format_date(date_time: Option<rbatis::rbdc::DateTime>) -> String {
    match date_time {
        Some(dt) => {
            let formatted = dt.format("YYYY/MM/DD").to_string();
            formatted
        },
        None => "".to_string(),
    }
}


// 解析时间
pub fn parse(d: &str) -> DateTime<Tz> {
    let tz = timezone();

    let date = NaiveDateTime::parse_from_str(d, "%Y-%m-%d %H:%M:%S").unwrap_or_default();

    tz.from_utc_datetime(&date)
}

// 解析时间戳
pub fn from_timestamp(t: i64) -> DateTime<Tz> {
    let tz = timezone();
    let date = DateTime::from_timestamp(t, 0).unwrap_or_default();
    tz.from_utc_datetime(&date.naive_utc())
}


#[inline]
pub fn time_difference(input_time: &str) -> String {
    match NaiveDateTime::parse_from_str(input_time, "%Y-%m-%d %H:%M:%S") {
        Ok(dt) => {
            let parsed_time = dt.and_local_timezone(Shanghai).unwrap();
            let current_time_shanghai = Local::now().with_timezone(&Shanghai);
            let duration = current_time_shanghai.signed_duration_since(parsed_time);
            if duration.num_seconds() < 60 {
                "刚刚".to_string()
            } else if duration.num_hours() < 1 {
                format!("{} 分钟前", duration.num_minutes())
            } else if duration.num_hours() < 24 {
                format!("{} 小时前", duration.num_hours())
            } else if duration.num_days() < 30 {
                format!("{} 天前", duration.num_days())
            } else if duration.num_days() < 365 {
                let months = (duration.num_days() as f64 + 14.5).floor() / 30.0; // 更准确地计算月份
                format!("{} 个月前", months.round() as i32)
            } else {
                parsed_time.format("%Y-%m-%d %H:%M:%S").to_string()
            }
        },
        Err(e) => {
            eprintln!("Error parsing datetime: {:?}", e);
            String::from("时间格式错误")
        }
    }
}
#[test]
fn test_time_difference() {
    // Test case 1: input time is less than 1 minute ago
    // let input_time = "2023-03-25 12:00:00";
    // let expected_result = "just now";
    // assert_eq!(time_difference(input_time), expected_result);

    // Test case 2: input time is less than 1 hour ago
    let input_time = "2024-07-13 22:41:00";
    let expected_result = "30 分钟 以前";
    println!("=============={:}",time_difference(input_time));
    //assert_eq!(time_difference(input_time), expected_result);

    // Test case 3: input time is less than 24 hours ago
    // let input_time = "2024-07-12 12:00:00";
    // let expected_result = "24 小时 以前";
    // assert_eq!(time_difference(input_time), expected_result);
    //
    // // Test case 4: input time is less than 30 days ago
    // let input_time = "2023-02-25 12:00:00";
    // let expected_result = "30 天 以前";
    // assert_eq!(time_difference(input_time), expected_result);
    //
    // // Test case 5: input time is less than 1 year ago
    // let input_time = "2022-03-25 12:00:00";
    // let expected_result = "12 月 以前";
    // assert_eq!(time_difference(input_time), expected_result);
    //
    // // Test case 6: input time is more than 1 year ago
    // let input_time = "2021-03-25 12:00:00";
    // let parsed_time = DateTime::parse_from_str(input_time, "%Y-%m-%d %H:%M:%S").unwrap().with_timezone(&Utc);
    // let expected_result = parsed_time.format("%Y-%m-%d %H:%M:%S").to_string();
    // assert_eq!(time_difference(input_time), expected_result);
    //
    // // Test case 7: input time format is incorrect
    // let input_time = "2023-03-25 12:00";
    // let expected_result = "时间格式错误";
    // assert_eq!(time_difference(input_time), expected_result);
}